package midalgorithms.other;

import java.util.Stack;

public class _02EvalRPN {
    public static int evalRPN(String[] tokens) {
        //  逆波兰表达式
        Stack<String> stack = new Stack<>();
        //  遍历数组
        for (String token : tokens) {
            if (isNum(token)) {
                stack.push(token);
                continue;
            }
            //  执行到此处说明遇上了运算符
            int b = Integer.parseInt(stack.pop());
            int a = Integer.parseInt(stack.pop());
            int res = switch (token) {
                case "+" -> a + b;
                case "*" -> a * b;
                case "-" -> a - b;
                case "/" -> a / b;
                default -> 0;
            };
            stack.push(String.valueOf(res));
        }
        return Integer.parseInt(stack.peek());
    }

    private static boolean isNum(String token) {
        return !token.equals("+") && !token.equals("-") && !token.equals("*") && !token.equals("/");
    }
}
